import Vue from 'vue'
import Vuex from 'vuex'
import createPersistedState from "vuex-persistedstate"
import user from './modules/user'
import lesson from './modules/lesson'
import live from './modules/live'
import search from './modules/search'
import {
  StudentAsyncRoutesMap,
  TeacherAsyncRouterMap,
  LeaderAsyncRouterMap,
  ConstantRouterMap
} from '@/router/index'
import { hasPermission } from '@/utils/permission'

Vue.use(Vuex)

export default new Vuex.Store({
  plugins: [createPersistedState({
    storage:window.sessionStorage,
    reduce(val) {
      return {
        assessmentData: val.user
      }
    }
  })],
  modules: {
    user,
    lesson,
    app,
    live,
    search
  },
  state: {
    fullScreeLoadingOption: {
      fullscreen: true,
      lock: true,
      text: '加载中...',
      background: 'rgba(244, 244, 245,0.85)',
    },
    addRouters: [],
    routers: ConstantRouterMap,
  },
  mutations: {
    SET_ROUTERS(state, routers) {
      state.addRouters = routers;
      state.routers = ConstantRouterMap.concat(routers);
    },
  },
  actions: {
    generateRoutes({ commit }, data) {
      return new Promise((resolve, reject) => {
        const {
          roles
        } = data;
        const {
          currentRoleType
        } = data;
        let asyncRouterMap = undefined;
        switch (currentRoleType) {
          case '0':
            asyncRouterMap = StudentAsyncRoutesMap;
            break;
          case '1':
            asyncRouterMap = TeacherAsyncRouterMap;
            break;
          case '2':
            asyncRouterMap = LeaderAsyncRouterMap;
            break;
          default:
            reject("不存在当前用户类型：" + currentRoleType);
            break;
        }
        const accessedRouters = asyncRouterMap.filter(v => {
          if (hasPermission(roles, v)) {
            if (v.children && v.children.length > 0) {
              v.children = v.children.filter(child => {
                if (hasPermission(roles, child)) {
                  return child
                }
                return false;
              });
              return v
            } else {
              return v
            }
          } else {
            return false;
          }
        });

        commit('SET_ROUTERS', accessedRouters);
        resolve(accessedRouters);
      });
    },
  },
  getters: {
    routers(state) {
      return state.routers;
    },
    addRouters(state) {
      return state.addRouters;
    },
  }
})